package com.leo.springbootmultithreadbasic.synchronizedkey.deadlock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Leo
 * @version V1.0
 */
public class MyThread extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(MyThread.class);


    private MyService myService;

    public MyThread(MyService myService) {
        this.myService = myService;
    }


    private String username;

    public void setUsername(String username) {
        this.username = username;
    }

    public Object object1 = new Object();
    public Object object2 = new Object();


    @Override
    public void run() {
        if ("A".equals(username)) {
            synchronized (object1) {
                logger.info("username: {}", username);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (object2) {
                    logger.info("进入synchronized (object2)");
                }
            }
        }

        if ("B".equals(username)) {
            synchronized (object2) {
                logger.info("username: {}", username);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (object1) {
                    logger.info("进入synchronized (object1)");
                }
            }
        }
    }
}
